<script setup>
import {computed, onUnmounted, ref} from 'vue';
import {ElMessage, ElImage} from 'element-plus';
import {Star, StarFilled, Message} from '@element-plus/icons-vue';
import {useRoute} from "vue-router";
import api from "@/api/index.js";
import {useStore} from "vuex";
import cache from "@/utils/cacheGetter.js";

const baseURL = api.getInstance().defaults.baseURL
const route = useRoute()
const targetId = route.params?.id
const tags = ref([])
const category = ref({categoryId: 0, categoryName: '未分类'})
const store = useStore()
const isAuthenticated = computed(() => {
  return store.getters?.isAuthenticated
})
const resourceDetail = ref({
  resourceId: 1,
  imgPath: '',
  // imgPath: '/ele.png',
  title: 'Vue3 深度指南',
  description: '全面讲解Vue3核心特性与实践',
  content: `

  `,
  categoryId: 1,
  authorId: 1,
  createdAt: '2023-08-01',
  updatedAt: '2023-08-10',

});

const getResourceById=()=>{
  return api.get('resource/' + targetId).then(resp => {
    resourceDetail.value = resp.data
    fetchAuthorProfile(resourceDetail.value.authorId)
    fetchCategoryByResourceId(resourceDetail.value.categoryId)
  })
}

const comments = ref([
  {
    commentId: 1,
    userId: 1,
    resourceId: 1,
    comment: '非常棒的教程！',
    commentAt: '2023-08-15'
  }
]);
const commentPagination = ref({
  pageNum:1,
  pageSize:10,
  pageTotal:0
})
const fetchComments = ()=>{
  api.getPageNoQuery(`userComment/resource/${targetId}`,commentPagination.value).then(resp=>{
    console.log(resp.data)
    comments.value = resp.data.records
    commentPagination.value.pageTotal = resp.data.total
  }).catch(e=>{
    comments.value = {
      commentId: 1,
      userId: 0,
      resourceId: 1,
      comment: '评论区加载失败！',
      commentAt: '2023-08-15'
    }
  })
}
const handleCommentSizeChange = (size)=>{
  commentPagination.value.pageSize = size
  fetchComments()
}
const handleCommentCurrentChange = (current)=>{
  commentPagination.value.pageNum = current
  fetchComments()
}
const newComment = ref('');


// 评论提交
const handleComment = () => {
  if (!newComment.value.trim()) return;

  let commentArg = {
    commentId: comments.value.length + 1,
    userId: 0, // 用户ID会在后端补全
    resourceId: resourceDetail.value.resourceId,
    comment: newComment.value
  }
  api.post('userComment/sendComment', commentArg).then(res => {
    fetchComments();
    ElMessage.success('评论成功');
  }).catch(e => {
    ElMessage.error('评论失败');
  })
  newComment.value = '';
};

const fetchTagsByResourceId = () => {
  api.get(`resourceTag/getByResourceId/${targetId}`).then(res => {
    tags.value = res.data;
  });
};

const fetchCategoryByResourceId = (categoryId) => {
  api.get(`category/get/${categoryId}`).then(res => {
    if(res.data){
      category.value = res.data;
    }else {
      category.value = {categoryId: 0, categoryName: '未分类'}
    }
  }).catch(err => {
    category.value = {categoryId: 0, categoryName: '分类获取失败'}
    console.log(err)
  })
};

const rate = ref(0)
const rateCount = ref(0)
const hasRated = ref(false)
const fetchUserRating = ()=>{
  api.get(`userRating/resource/${targetId}`).then(res => {
    if(res.data){
      rate.value = res.data.ratingScore;
      rateCount.value = res.data.ratingCount;
    }else {
      rate.value = 0;
      rateCount.value = 0;
    }
  }).catch(err => {
    rate.value = 0;
    rateCount.value = 0;
  })
}

const fetchHasRated = ()=>{
  api.get(`userRating/resource/${targetId}/hasRated`).then(res => {
    hasRated.value = res.data;
    console.log(hasRated.value);
  }).catch(err => {
    hasRated.value = false;
  })
}
const sendUserRating = (value)=>{
  api.post(`userRating/resource/${targetId}/send`,{ratingValue:value}).then(res => {
    fetchUserRating();
    fetchHasRated();
    ElMessage.success('评分成功');
  }).catch(err => {
    ElMessage.error('评分失败');
  })
}
const handleRateChange = (value)=>{
  sendUserRating(value);
}

let studyDuration = 0;
const timer = setInterval(() => {
  studyDuration++;
  // console.log(studyDuration);
}, 1000);


const hasCollection = computed(
    {
      get() {
        return cache.get('userCollection/user',targetId)
      },
      set(newValue) {

      }
    }
)
const toggleFavorite = ()=>{
  if (hasCollection.value) {
    api.delete('userCollection/user/delete/' + targetId).then(resp=>{
      ElMessage.success('取消收藏成功')
      cache.flush('userCollection/user',targetId)
    })
  } else {
    api.post('userCollection/user/add/'+targetId).then(resp=>{
      ElMessage.success('收藏成功')
      cache.flush('userCollection/user',targetId)
    })
  }
}
const authorProfile = ref({collectedCount:0,avgScore:0})
const fetchAuthorProfile = (id)=>{
  api.get('user/authorProfile/'+id).then(resp=>{
    authorProfile.value = resp.data
  })
}

//初始化
getResourceById()
fetchTagsByResourceId();
fetchComments();
fetchUserRating();
fetchHasRated();
fetchAuthorProfile();
onUnmounted(e=>{
  clearInterval(timer);
  if(studyDuration>3) {
    api.post('userLearningHistory/sendHistory', {resourceId: targetId, studyDuration: studyDuration}).then(resp => {
      ElMessage.success(`您查看了${studyDuration}秒`);
    }).catch(e => {
      console.log(e);
    })
  }
  console.log("被卸载")
})
</script>

<template>
  <div class="detail-container" :style="{'--background-image': `url(${resourceDetail.imgPath?baseURL+'resource/download/'+resourceDetail.imgPath:'/fallback.png'})`}">
    <!-- 资源详情区域 -->
    <el-card class="resource-card">
      <el-image
          :src="resourceDetail.imgPath?baseURL+'resource/download/'+resourceDetail.imgPath:'/fallback.png'"
          fit="cover"
          class="resource-image"
      />

      <el-row :gutter="20" class="mt-20">
        <el-col :span="24"> <!-- 修改为全宽布局 -->
          <div class="title-area">
            <el-dropdown>
              <span class="el-dropdown-link">
                <el-avatar :size="80" :src="baseURL+'user/download/'+cache.get('user',resourceDetail.authorId)?.avatar" class="user-avatar"/>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item disabled style="color: black">
                    作者名称:{{ cache.get('user',resourceDetail.authorId)?.username }}
                  </el-dropdown-item>
                  <el-dropdown-item disabled>
                    <el-tag>
                      <el-icon>
                        <StarFilled/>
                      </el-icon>
                      收藏数:{{authorProfile.collectedCount}}
                    </el-tag>
                    &nbsp;
                    <el-tag type="success">
                      <el-icon>
                        <StarFilled/>
                      </el-icon>
                      总评分:{{authorProfile.avgScore}}
                    </el-tag>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <h1>{{ resourceDetail.title }}</h1>
            <el-button
                type="warning"
                :icon="hasCollection ? StarFilled : Star"
                @click="toggleFavorite"
                circle
                class="favorite-btn"
            />
          </div>
          <div class="meta-info">
            <el-tag type="danger">分类: {{ category.categoryName }}</el-tag>
          </div>
          <el-card class="rating-card">
            <div class="rating-content">
              <el-rate 
                v-model="rate"
                allow-half
                :max="5"
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                void-color="#EFF2F7"
                :size="28"
                :disabled="!isAuthenticated || hasRated"
                @change="handleRateChange"
              />
              <div class="rating-text">
                <span class="rating-value">{{ rate.toFixed(1) }}</span>
                <span class="rating-tip">综合评分<span style="color:red">{{!isAuthenticated?'（先登录后才能评分）':''}}</span></span>
              </div>
            </div>
            <div class="rating-footer">已有 {{ rateCount }} 人评价</div>
          </el-card>

          <div class="meta-info">
            <el-tag type="info">作者ID: {{ resourceDetail?.authorId }}</el-tag>
            <el-tag type="success">创建时间: {{ resourceDetail.createdAt }}</el-tag>
            <el-tag v-for="tag in tags">
              {{tag.tagName}}
            </el-tag>
          </div>
          <p class="description">{{ resourceDetail.description }}</p>
          <div class="content" v-html="resourceDetail.content"></div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 评论区 -->
    <el-card class="comment-section mt-20">
      <template #header>
        <div class="comment-header">
          <el-icon>
            <Message/>
          </el-icon>
          <span>评论区（{{ comments.length }}条）</span>
        </div>
      </template>

      <el-form @submit.prevent="handleComment">
        <el-input
            v-model="newComment"
            type="textarea"
            :rows="3"
            :placeholder="isAuthenticated ? '请输入您的评论...' : '请先登录'"
            class="mb-10"
            :disabled="!isAuthenticated"
        />
        <el-form-item class="text-right">
          <el-button type="primary" :disabled="!isAuthenticated" native-type="submit">发表评论</el-button>
        </el-form-item>
      </el-form>
      <el-pagination
          :current-page="commentPagination.current"
          :page-size="commentPagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="commentPagination.total"
          class="pagination"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleCommentSizeChange"
          @current-change="handleCommentCurrentChange"
      />
      <el-timeline>
        <el-timeline-item
            v-for="item in comments"
            :key="item.commentId"
            :timestamp="item.commentAt"
            placement="top"
        >
          <el-card class="comment-item">
            <div class="comment-header">
              <el-avatar :size="32" :src="baseURL+'user/download/'+cache.get('user',item.userId)?.avatar"/>
              <span class="user-id">{{ cache.get('user',item.userId)?.username }}</span>
            </div>
            <p class="comment-content">{{ item.comment }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <el-pagination
          :current-page="commentPagination.current"
          :page-size="commentPagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="commentPagination.total"
          class="pagination"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleCommentSizeChange"
          @current-change="handleCommentCurrentChange"
      />
    </el-card>
  </div>
</template>

<style scoped>
:root {
  --background-image: url('/vite.svg');
}
.content {
  & :deep(pre) {
    text-align: left;
    background: #f6f8fa;
    padding: 15px;
    border-radius: 6px;
    overflow-x: auto;
  }

  & :deep(code) {
    text-align: left; /* 确保代码块左对齐 */
    font-family: Monaco, Consolas, monospace;
  }
}

/* 新增标题区域样式 */
.title-area {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.favorite-btn {
  font-size: 24px;
  padding: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.detail-container::before{
  z-index: -1;
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: var(--background-image) 50% 0;
  background-size: cover;
  filter: blur(5px);
  opacity: 0.1;
}

/* 删除原有右侧栏样式 */
.detail-container {
  position: relative;
  z-index: 0;
  padding: 50px 15%;
}

.resource-image {
  width: 100%;
  height: 400px;
  border-radius: 8px;
}

.meta-info {
  margin: 15px 0;
  display: flex;
  gap: 10px;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
}

.comment-item {
  margin-top: 10px;

  .comment-header {
    margin-bottom: 10px;
  }

  .user-id {
    font-weight: bold;
    margin-left: 10px;
  }
}

.comment-content {
  text-align: left;
  margin: 0;
  color: #666;
}

/* 新增内容样式 */
.content {
  line-height: 1.8;

  & :deep(img) {
    max-width: 100%;
    margin: 15px 0;
    border-radius: 6px;
  }

  & :deep(p) {
    margin: 1em 0;
  }

  & :deep(pre) {
    background: #f6f8fa;
    padding: 15px;
    border-radius: 6px;
    overflow-x: auto;
  }

  & :deep(code) {
    font-family: Monaco, Consolas, monospace;
  }
}

.text-right {
  text-align: right;
}

.mt-20 {
  margin-top: 20px;
}

.mb-10 {
  margin-bottom: 10px;
}

/* 新增评分卡片样式 */
.rating-card {
  margin: 15px 0;
  background: linear-gradient(145deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.rating-content {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 18px;
}

.rating-text {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.rating-value {
  font-size: 32px;
  font-weight: 700;
  color: var(--el-color-warning);
  line-height: 1;
}

.rating-tip {
  color: #909399;
  font-size: 14px;
}

.rating-footer {
  border-top: 1px solid var(--el-border-color-light);
  padding: 12px 18px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  background: #f8f9fa;
}
</style>
